package com.matt.controller.group;


import com.dotflat.dashboard.service.DashboardService;
import com.dotflat.dashboard.util.PanelUtil;
import com.dotflat.dashboard.vo.*;
import com.dotflat.util.excelUtil.ExcelDataVo;
import com.dotflat.util.excelUtil.ExcelUtil;
import com.dotflat.util.excelUtil.PackExcelSheetsDataUtil;
import com.dotflat.util.excelUtil.StringUtils;
import com.matt.commons.model.StatusResponse;
import com.matt.domain.Children;
import com.matt.foundation.ext.aliyun.OSSProcessService;
import com.matt.foundation.model.MemVerificationCache;
import com.matt.foundation.utils.DateUtil;
import com.matt.foundation.utils.IpHelper;
import com.matt.service.ChildrenService;
import com.matt.service.remoteCall.DTO.AreaListDTO;
import com.matt.service.remoteCall.DTO.AreaStaffDTO;
import com.matt.service.remoteCall.DTO.GroupDTO;
import com.matt.service.remoteCall.DTO.SsoAreaDTO;
import com.matt.service.remoteCall.SsoCallService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.joda.time.DateTime;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.util.*;
import java.util.stream.Collectors;

import static com.matt.foundation.constant.RequestConstant.TICKET;

@Controller
@RequestMapping("/web/group")
@Api(tags = "Web集团 - ")
public class WebGroupController {

    @Autowired
    private SsoCallService ssoCallService;

    @Autowired
    private ChildrenService childrenService;

    @Autowired
    protected MemVerificationCache cache;

    @Autowired
    private DashboardService dashboardService;

    @Autowired
    private OSSProcessService ossProcessService;

    @Value("${aliyun.oss.fileServerPrefix}")
    private String IMG_SERVICE_PREFIX;

    @PostMapping(value = "/group_pass_login")
    @ResponseBody
    @ApiOperation(value = "集团 - 登录")
    public StatusResponse groupPassLogin(String mobile, String password,@RequestHeader(required = false) String platformId, HttpServletRequest request) {
        String ticket = ssoCallService.groupPassLogin(mobile, password, IpHelper.getRequestIpAddr(request), 1,platformId);
        return StatusResponse.success(ticket);
    }

    @PostMapping(value = "/group_count")
    @ResponseBody
    @ApiOperation(value = "集团 - 统计")
    public StatusResponse groupCount(@RequestHeader(TICKET) String ticket) {
        //集团下所有园区
        List<SsoAreaDTO> areaDTOList = ssoCallService.getGroupAllArea(ticket);
        //集团下所有用户园区关联
        List<AreaStaffDTO> areaStaffList = ssoCallService.getStaffAreaList(ticket);

        List<String> list = areaDTOList.stream().map(k -> k.getId()).collect(Collectors.toList());
        String[] areaIds = list.toArray(new String[list.size()]);
        //总集团园学生
        List<Children> childrenList = dashboardService.findAllByStatusAndAreaIdIn(1, areaIds);

        //综合信息对象
        InformationVO information = dashboardService.information(areaDTOList);
        information.setTeacherCount(areaStaffList.size());
        information.setStaffCount(areaStaffList.size());

        List<ClassTypeCountVO> classTypeCount = dashboardService.classTypeCount(list);

        List<AreaClassTypeCountVO> areaClassTypeCount_1 = dashboardService.areaClassTypeCount(list);

        List<AreaClassTypeCountVO> areaClassTypeCount = new ArrayList<>();
        for (int i = 0; i < areaClassTypeCount_1.size(); i++) {
            List<String> areaId = new ArrayList<>();
            areaId.add(areaClassTypeCount_1.get(i).getAreaId());
            //年级分布
            List<GradeCountVO>  gradeCountVOList = dashboardService.grade(areaId);

            AreaClassTypeCountVO areaClassTypeCountVO = new AreaClassTypeCountVO();
            areaClassTypeCountVO.setAreaId(areaClassTypeCount_1.get(i).getAreaId());
            List<ClassTypeCountVO> classTypeCountVOList = new ArrayList<>();
            for (int j = 0; j < gradeCountVOList.size(); j++) {
                ClassTypeCountVO classTypeCountVO = new ClassTypeCountVO();
                classTypeCountVO.setName(gradeCountVOList.get(j).getName());
                classTypeCountVO.setClassCount(gradeCountVOList.get(j).getClassesCount());
                classTypeCountVO.setChildrenCount(gradeCountVOList.get(j).getChildrenCount());
                classTypeCountVOList.add(classTypeCountVO);
            }
            areaClassTypeCountVO.setList(classTypeCountVOList);
            areaClassTypeCount.add(areaClassTypeCountVO);
        }
        //教师、教职工分布
        List<StaffCountVO> staffCountVOList = PanelUtil.getStaffCountVO(areaDTOList, areaStaffList, information.getStaffCount());

        //幼儿分布
        List<ChildrenCountVO> childrenCountVOList = PanelUtil.getChildrenCountVO(areaDTOList, childrenList, information.getChildrenCount());

        //集团 - 园区的班级总数
        List<Map> list1 = dashboardService.getAreaIdCountList(list);

        //地区分布
        List<AreaAllVO> list2 = PanelUtil.getAreaAll(areaDTOList, list1, childrenCountVOList, staffCountVOList, areaClassTypeCount);


        Map map = new HashMap();
        //集团统计
        map.put("groupCount", information);
        //托班，早教数
        map.put("classTypeCount", classTypeCount);

        list2 = list2.stream().sorted(Comparator.comparing(AreaAllVO::getChildrenCount).reversed()).collect(Collectors.toList());
        //园区详情
        map.put("areaCount", list2);

        return StatusResponse.success(map);
    }


    @PostMapping(value = "/info")
    @ResponseBody
    @ApiOperation(value = "集团 - 信息")
    public StatusResponse info(@RequestHeader(TICKET) String ticket,@RequestHeader(required = false) String platformId) {
        Map response = ssoCallService.getPermissionInfoV2(ticket, 1,platformId);
        List<GroupDTO> list = ssoCallService.getStaffGroupList(ticket);

        Map map = new HashMap();
        if (list.size() > 0) {
            map.put("group", list.get(0));
        }

        //集团下所有园区
        List<SsoAreaDTO> areaDTOList = ssoCallService.getGroupAllArea(ticket);

        List<AreaListDTO> areaList = new ArrayList<>();
        for (int i = 0; i < areaDTOList.size(); i++) {
            AreaListDTO areaListDTO = new AreaListDTO();
            areaListDTO.setAreaId(areaDTOList.get(i).getId());
            areaListDTO.setAreaName(areaDTOList.get(i).getAreaName());
            areaListDTO.setRoleNames("");
            areaList.add(areaListDTO);
        }
        map.put("area", response.get("area"));
        map.put("role", response.get("role"));
        map.put("roles", response.get("roles"));
        map.put("areaList", areaList);
        map.put("staff", response.get("staff"));
        return StatusResponse.success(map);
    }


    @ApiOperation(value = "导出 - 集团学生", httpMethod = "POST")
    @RequestMapping(value = "/export_group_children", method = RequestMethod.POST)
    public StatusResponse exportCheckRecordByClassId(@RequestHeader(TICKET) String ticket) {
        //集团下所有园区
        List<SsoAreaDTO> areaDTOList = ssoCallService.getGroupAllArea(ticket);

        List<String> list = areaDTOList.stream().map(k -> k.getId()).collect(Collectors.toList());
        String[] areaIds = list.toArray(new String[list.size()]);
        //总集团园学生
        List<Children> childrenList = dashboardService.findAllByStatusAndAreaIdIn(1, areaIds);
        for (int i = 0; i < childrenList.size(); i++) {
            for (int j = 0; j < areaDTOList.size(); j++) {
                if (StringUtils.equals(childrenList.get(i).getAreaId(), areaDTOList.get(j).getId())) {
                    childrenList.get(i).setAreaId(areaDTOList.get(j).getAreaName());
                }
            }
        }
        ExcelUtil<Children> util = new ExcelUtil<Children>(Children.class);
        String fileUrl = util.exportExcel(childrenList, "学生签到记录");
        String tempPath = "";
        if (File.separatorChar == '/') {
            tempPath = "/tmp/check_sheet";
        } else {
            tempPath = "d:";
        }
        File outputFile = new File(tempPath + "/" + fileUrl);
        String uploadPath = "teach/file/children_export_excel/" + DateTime.now().toString("yyyy-MM") + "/" + fileUrl;
        String relativePath = ossProcessService.aliyunOssUpload(uploadPath, outputFile);
        String uploadedResult = IMG_SERVICE_PREFIX + relativePath;
        outputFile.deleteOnExit();
        outputFile.delete();
        return StatusResponse.success(uploadedResult);
    }

    /**
     * 多个导出sheet
     */
    @PostMapping(value = "/exportChildrenCheckList")
    @ResponseBody
    @ApiOperation(value = "导出 - 集团考勤")
    @ApiImplicitParams({
            @ApiImplicitParam(paramType = "header", name = "ticket", value = "票据", required = true, dataType = "string"),
            @ApiImplicitParam(paramType = "query", name = "date", value = "考勤时间yyyy-MM-dd", required = true, dataType = "string"),
    })
    public StatusResponse exportTeenagerMoreSheet(HttpServletResponse response, @RequestHeader(TICKET) String ticket, String date) {
        date +=" 00:00:00";
        //集团下所有园区
        List<SsoAreaDTO> areaDTOList = ssoCallService.getGroupAllArea(ticket);

        List<String> list = areaDTOList.stream().map(k -> k.getId()).collect(Collectors.toList());

        String[] areaIds = list.toArray(new String[list.size()]);
        //总集团园学生
        List<Children> childrenList = dashboardService.findAllByStatusAndAreaIdIn(1, areaIds);
        //学生考勤列表
        List<ChildrenCheckVO> childrenCheckList = dashboardService.getChildrenCheck(list, date);
        List<String> dateList = new ArrayList<>();
        //当月所有天
        List<String> dateList1 = DateUtil.getDayByMonth(DateUtil.parseToDay(date));

        List<String> stringList = new ArrayList<>();
        stringList.add("学生名字");
        stringList.add("园区");

        dateList.addAll(stringList);
        dateList.addAll(dateList1);
        // 考勤信息
        List<Map<String, Object>> list1 = new ArrayList<>();
        // 请假信息
        List<Map<String, Object>> list2 = new ArrayList<>();
        // 生病信息
        List<Map<String, Object>> list3 = new ArrayList<>();
        for (int i = 0; i < childrenList.size(); i++) {
            Map<String, Object> map1 = new HashMap<>();
            Map<String, Object> map2 = new HashMap<>();
            Map<String, Object> map3 = new HashMap<>();

            map1.put("学生名字", childrenList.get(i).getName());
            map2.put("学生名字", childrenList.get(i).getName());
            map3.put("学生名字", childrenList.get(i).getName());

            for (int k = 0; k < areaDTOList.size(); k++) {
                if (StringUtils.equals(childrenList.get(i).getAreaId(), areaDTOList.get(k).getId())) {
                    map1.put("园区", areaDTOList.get(k).getAreaName());
                    map2.put("园区", areaDTOList.get(k).getAreaName());
                    map3.put("园区", areaDTOList.get(k).getAreaName());
                }
            }
            for (int j = 0; j < childrenCheckList.size(); j++) {
                if (Objects.nonNull(childrenCheckList.get(j).getCheckInTime()) &&
                        StringUtils.equals(childrenCheckList.get(j).getChildrenId(), childrenList.get(i).getId())) {
                    if (childrenCheckList.get(j).getStatus() == 1) {
                        String check = childrenCheckList.get(j).getCheckInTime();
                        map1.put(childrenCheckList.get(j).getCheckInTime(), childrenCheckList.get(j).getCheckInTime());
                    }
                    if (childrenCheckList.get(j).getStatus() == 4) {
                        map2.put(childrenCheckList.get(j).getCheckInTime(), "请假" );
                    }
                    if (childrenCheckList.get(j).getHealthyStatus() == 1) {
                        map3.put(childrenCheckList.get(j).getCheckInTime(),"病假");
                    }
                }
            }
            list1.add(map1);
            list2.add(map2);
            list3.add(map3);
        }
        // 封装需要导出的数据
        List<ExcelDataVo> excelDataVoList = new ArrayList<>();

        // 封装学生信息
        ExcelDataVo excelDataSheetOne = new ExcelDataVo();
        excelDataSheetOne.setSheetName("学生考勤信息");
        excelDataSheetOne.setSheetTopColHeaderTitle("学生考勤信息");
        excelDataSheetOne.setSheetTopColHeaderName(dateList.toArray(new String[dateList.size()]));
        excelDataSheetOne.setSheetTopColHeaderAttribute(dateList.toArray(new String[dateList.size()]));
        excelDataSheetOne.setSheetDataList(list1);
        excelDataVoList.add(excelDataSheetOne);

        // 封装学校信息
        ExcelDataVo excelDataSheetTwo = new ExcelDataVo();
        excelDataSheetTwo.setSheetName("学生请假信息");
        excelDataSheetTwo.setSheetTopColHeaderTitle("学生请假信息");
        excelDataSheetTwo.setSheetTopColHeaderName(dateList.toArray(new String[dateList.size()]));
        excelDataSheetTwo.setSheetTopColHeaderAttribute(dateList.toArray(new String[dateList.size()]));
        excelDataSheetTwo.setSheetDataList(list2);
        excelDataVoList.add(excelDataSheetTwo);

        // 封装其他信息
        ExcelDataVo excelDataSheetThree = new ExcelDataVo();
        excelDataSheetThree.setSheetName("学生异常信息");
        excelDataSheetThree.setSheetTopColHeaderTitle("学生异常信息");
        excelDataSheetThree.setSheetTopColHeaderName(dateList.toArray(new String[dateList.size()]));
        excelDataSheetThree.setSheetTopColHeaderAttribute(dateList.toArray(new String[dateList.size()]));
        excelDataSheetThree.setSheetDataList(list3);
        excelDataVoList.add(excelDataSheetThree);
        String url= "";
        // 导出数据
        try {
            url  = new PackExcelSheetsDataUtil().packExcelSheetsData(response, "学生基础信息", excelDataVoList);
        } catch (Exception e) {
            throw new Exception("导出异常!");
        }finally {
            File outputFile = new File(url);
            String uploadPath = "teach/file/children_export_excel/" + DateTime.now().toString("yyyy-MM") + "/集团考勤报表.xlsx";
            String relativePath = ossProcessService.aliyunOssUpload(uploadPath, outputFile);
            String uploadedResult = IMG_SERVICE_PREFIX + relativePath;
            return StatusResponse.success(uploadedResult);
        }
    }


}
